
/**
 * 
 * @param {*} reducer 处理器
 * @param {*} preloadedState 初始状态
 */
const createStore = (reducer, preloadedState) => {
    let state = preloadedState || {};
    let listeners = [];
    function getState() {
        return state;
    }
    // 添加订阅，返回销毁函数
    function subscribe(listener) {
        listeners.push(listener);
        return () => {
            let index = listeners.indexOf(listener);
            listeners.splice(index, 1);
        }
    }
    // 计算状态，发布
    function dispatch(action) {
        state = reducer(state, action);
        listeners.forEach(listener => listener());
        return state;
    }

    dispatch({ type: '@@REDUX/INIT' })
    const store = {
        getState,
        subscribe,
        dispatch
    }
    return store;
}
export default createStore;